<template>
	<view :class="'audio-message ' + (isMine ? 'my-audio' : '')" @click="handlePlayAudioMessage">
		<image v-if="message.flow==='in'" class="audio-icon audio-icon-in" :src="isPlay ? audioPlayImg : audioImg"></image>
		<view>{{message.payload.second}}s</view>
		<image v-if="message.flow==='out'" class="audio-icon" :src="isPlay ? audioPlayImg : audioImg"></image>
	</view>
</template>

<script>
export default {
	data() {
		return {
			audio: {},
			isPlay: false,
			audioImg: require('../../../../static/assets/audio1.png'),
			audioPlayImg: require('../../../../static/assets/audio2.gif')
		};
	},

	components: {},
	props: {
		message: {
			type: Object,
			default: () => {}
		},
		isMine: {
			type: Boolean,
			default: true
		}
	},
	watch: {
		message: {
			handler: function(newVal) {
				this.setData({
					message: newVal
				});
			},
			immediate: true,
			deep: true
		}
	},

	beforeMount() {
		this.audio = uni.createInnerAudioContext();
		this.audio.onPlay(() => {
			this.isPlay = true
		});
		this.audio.onEnded(() => {
			this.isPlay = false
		});
		this.audio.onError(e => {
			console.error(e, 'onError');
			// ios 音频播放无声，可能是因为系统开启了静音模式
			uni.showToast({
				icon: 'none',
				title: '该音频暂不支持播放'
			});
		});
	},

	methods: {
		handlePlayAudioMessage() {
			this.audio.src = this.message.payload.url;
			this.audio.play();
		}
	}
};
</script>
<style>
@import './index.css';
</style>
